package com.muki.uri.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.JMSException;

import org.apache.log4j.Logger;

import com.muki.jms.JmsSender;

/**
 * uri队列监听内核
 * @author ljh_2017
 *
 */
public class UriRegisterationCore {

	private final Logger log = Logger.getLogger(UriRegisterationCore.class);
	//存储,将uri缓存在Map中
	//可扩展redis
	private static final Map<String,List<String>> uris = new HashMap<>();
	
	//负责控制过滤接口
	private final FilterChain chain = new FilterChain();
	
	//调用入口
	private static final Map<String,UriGet> get = new HashMap<>();
	//消息发送者
	/**
	 * 负责将获取到的uri发送到
	 */
	private final JmsSender sender = new JmsSender();
	
	//单例模式
	private final static UriRegisterationCore core = new UriRegisterationCore();

	public static UriRegisterationCore getInstance() {
		return core;
	}

	/**
	 * 
	 * @param uri
	 */
	public void receive(RequestUri uri) {
		chain.doFilter(uri);
		chain.FilterLoader(uri);
		if(uri.check()) {
			String topic = uri.getFlagUri().getTopic();
			String url = uri.getFlagUri().getUri();
			try {
				boolean status = SpiderUriMemoryCache.putIfAbsent(topic, url);
				
				if(status) {
					log.info("发送 "+url+" 到 "+topic+" 队列下");
					sender.sendTextMsg(false, url, topic);
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Map<String,List<String>> getUriCollection() {
		return uris;
	}
	
	public static void getSpiderRunning(String topic,String url) {
		//get.doGet("topic", "http://geek.csdn.net/forum/AI");
		List<String> uri = uris.getOrDefault(topic, new ArrayList<>());
		UriGet uriget = get.getOrDefault(topic, null);
		if(uriget==null) {
			uriget = new UriGetor();
			new Thread(uriget).start();
			get.put(topic, uriget);
		} 
		uriget.doGet(topic, url);
		uri.add(url);
		uris.put(topic, uri);
	}
}
